//
//  OAIpdataBase.m
//  LongOA
//
//  Created by 耿用强 on 15/7/9.
//  Copyright (c) 2015年 耿用强. All rights reserved.
//

#import "OAIpdataBase.h"
#import "OAAccount.h"
#import "OAIpdataBase.h"
#import "OASet.h"
#import "P1ClientCreator.h"
#import "sqlite3.h"

#import "OAIdFac.h"

#import "SysPlanCheckRequest.h"
#import "SysPlanCheckResponse.h"
#import "PowerCheckRequest.h"
#import "PowerCheckResponse.h"

#define Kipdata   @"kipdata"
@implementation OAIpdataBase // 单实例
{
    NSMutableArray* loginAccounts; // 已经登陆的帐套
    NSMutableArray* allAccounts; // 所有帐套
    NSMutableDictionary* pools; // 服务器-连接池 对应表 [setid:LJClientPool]
    NSMutableDictionary* sets; // 服务器 [setid:OASet]
    LKDBHelper* dbhelper;
    NSMutableArray* modules;
}
static OAIpdataBase* instance = nil;

+ (void)saveIpandPortData:(NSDictionary *)data
{
    NSMutableArray*array=[NSMutableArray arrayWithArray:[OAIpdataBase getIpandPortData]];
    [array addObject:data];
    [[NSUserDefaults standardUserDefaults]setObject:array forKey:Kipdata];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+ (NSArray*)getIpandPortData
{
   NSArray*array=[[NSUserDefaults standardUserDefaults]objectForKey:Kipdata];
    if (array==nil) {
        array=[[NSArray alloc]init];
    }
    return array;
}

+ (OAIpdataBase*)shareInstance
{
    if (!instance)
    {
        @synchronized(self)
        {
            if (!instance)
            {
                instance = [[OAIpdataBase alloc]init];
            }
        }
    }
    return instance;
}

/// 获取新的ID
-(int)GetID:(NSString*) key
{
    NSString* where = [[NSString alloc] initWithFormat:@"id_key = '%@'", key];
    NSArray* facs = [OAIdFac searchWithWhere:where];
    OAIdFac* cur;
    if (facs.count > 0) {
        cur = facs[0];
    }
    else {
        cur = [[OAIdFac alloc] init];
        cur.id_key = key;
        cur.id_value = 10;
    }
    
    cur.id_value += 1;
    [cur saveToDB];
    
    return cur.id_value;
}

-(int)AddServiceWithIP:(NSString*)ip AndPort:(int)port AndAccounts:(NSArray *)accounts
{
    NSString * where = [NSString stringWithFormat:@"IP='%@' AND port=%i", ip, port];
    NSMutableArray* array = [OASet searchWithWhere:where orderBy:nil offset:0 count:100];
    
    OASet* newset = nil;
    if (array.count > 0)
    {
        newset = array[0];
        NSString* parms = [NSString stringWithFormat:@"'%@'", accounts[0]];
        for (int i = 1; i < accounts.count; i++)
        {
            parms = [NSString stringWithFormat:@"%@,'%@'", parms, accounts[i]];
        }
        
        [dbhelper executeDB:^(FMDatabase *db){
            NSString* sql = [NSString stringWithFormat:@"DELETE FROM OAAccount WHERE name not in (%@) AND setid=%i", parms, newset.setid];;
            [db executeUpdate:sql];
        }];
        
        for (NSString* accname in accounts) {
            
            where = [NSString stringWithFormat:@"setid=%i AND name = '%@'", newset.setid, accname];
            array = [OAAccount searchWithWhere:where orderBy:nil offset:0 count:100];
            if (array == 0)
            {
                OAAccount* account = [[OAAccount alloc] init];
                account.accountid = [self GetID:@"OAAccount_accountid"];
                account.setid = newset.setid;
                account.name = accname;
                [account saveToDB];                
            }
        }           
    }
    else
    {
        newset = [[OASet alloc] init];
        newset.setid = [self GetID:@"OASet_setid"];
        newset.stype = 1;
        newset.IP = ip;
        newset.port = port;
        newset.url = @"";
        newset.cusid = @"";
        newset.name = [[NSString alloc] initWithFormat:@"%@:%i",ip,port];
        [newset saveToDB];
        
        for (NSString* accname in accounts) {
            OAAccount* account = [[OAAccount alloc] init];
            account.accountid = [self GetID:@"OAAccount_accountid"];
            account.setid = newset.setid;
            account.name = accname;
            [account saveToDB];
        }        
    }
      
    return newset.setid;
}

-(instancetype)init
{
    self = [super init];
    dbhelper = [[LKDBHelper alloc] init];
    
    modules = [[NSMutableArray alloc] init];
    [modules addObject: [[Module alloc] initWithID:0 andName:@"内部邮件"]];
    [modules addObject: [[Module alloc] initWithID:0 andName:@"公告"]];
    [modules addObject: [[Module alloc] initWithID:0 andName:@"公文"]];
    
    return self;
}

- (NSArray*)allAccounts
{
//    NSLog(@"=");
//    NSLog(@"=%@=",self->allAccounts);
    return self->allAccounts;
}

- (NSArray*)loginAccounts
{
    return self->loginAccounts;
}

-(void)initAccounts
{
    // 从数据库读取现有帐套
    
    // 读取服务器
    sets = [[NSMutableDictionary alloc] init];
    
    NSMutableArray* allset = [OASet searchWithWhere:nil];
    
    for (OASet* set in allset) {
        [sets setObject:set forKey:[NSNumber numberWithInt:set.setid]];
    }
    // 连接池 使用时间才创建实例
    self->pools = [[NSMutableDictionary alloc] init];
    
    // 从数据库获取所有实例并将已经登录的放到 队列loginAccounts
    allAccounts = [OAAccount searchWithWhere:nil];
    loginAccounts = [[NSMutableArray alloc] init];
    
    // 模块权限ID列表
    NSMutableArray* module_ids = [[NSMutableArray alloc]init];
    for (Module* module in modules) {
        [module_ids addObject: [NSNumber numberWithInt:module.id]];
    }
    
    for (OAAccount* account in allAccounts)
    {
        account.hasCheck1 = NO;
        account.hasCheck2 = NO;
        account.hasLogin = NO;
        account.power1 = nil;
        account.power2 = nil;
        
        
        if (!account.token || [account.token  isEqual: @""]) {
            account.hasCheck1 = YES;
            account.hasCheck2 = YES;
            
            
        }
        else {
            //2015.09.17
            //NSLog(@"account=%@  token=%@  id=%i",account,account.token,account.setid);
            [[NSUserDefaults standardUserDefaults] setObject:account.token forKey:@"token"];
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%i",account.setid] forKey:@"setid"];
            [[NSUserDefaults standardUserDefaults] setObject:account.name forKey:@"accname"];
            //NSLog(@"token=%@  setid=%@  accname=%@",account.token,[NSString stringWithFormat:@"%i",account.setid],account.name);
            LJClientPool* pool = [self getPool:account.setid];
            
            SysPlanCheckRequest* request = [[SysPlanCheckRequest alloc] init];
            request.token = account.token;
            request.funcids = module_ids;
            
            [pool Doexecute:request
                   RspClass:[SysPlanCheckResponse class]
                     andMsg:@""
                    andView:nil
globalTimelinePostsWithBlock:^(id rsp) {
    SysPlanCheckResponse* rslt = rsp;
    if (rslt.ErrMsg) {
        NSLog(@"%@", rslt.ErrMsg);
    }
    else {
        account.power1 = rslt.hasPower;
    }
    account.hasCheck1 = YES;
}];
            
            PowerCheckRequest* request1 = [[PowerCheckRequest alloc] init];
            request1.token = account.token;
            request1.funcids = module_ids;
            
            [pool Doexecute:request1
                   RspClass:[PowerCheckResponse class]
                     andMsg:@""
                    andView:nil
globalTimelinePostsWithBlock:^(id rsp) {
    PowerCheckResponse* rslt = rsp;
    if (rslt.ErrMsg) {
        NSLog(@"%@", rslt.ErrMsg);
    }
    else {
        account.power2 = rslt.hasPower;
        account.hasLogin = YES;
        [loginAccounts addObject:account];
    }
    account.hasCheck2 = YES;
}];
            
        }
    }
    int i = 0;
    do {
        //[NSThread sleepForTimeInterval:0.2];
        //sleep(1);
//        NSLog(@"ready to runloop");
//        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
//        NSLog(@"runloop end");
        [NSThread sleepForTimeInterval:1];
        for (i = 0; i < allAccounts.count; i++)
        {
            OAAccount* account = allAccounts[i];
            if (!account.hasCheck1 || !account.hasCheck2) {
                break;
            }
        }
    } while (i < allAccounts.count);
}

-(LJClientPool*)getPool:(int)setid
{
    LJClientPool* rslt = [self->pools objectForKey:[NSNumber numberWithInt:setid]];
    if (rslt) {
        return rslt;
    }
    
    OASet* set = [self getSet:setid];
    if (set) {
        P1ClientCreator* creator = [[P1ClientCreator alloc] initWithIP:set.IP AndPort:set.port];
        rslt = [[LJClientPool alloc] initWithCreator:creator AndSize:5];
        [self->pools setObject:rslt forKey:[NSNumber numberWithInt:setid]];
    }
    return rslt;
}

-(OASet*)getSet:(int)setid
{
    OASet* rslt = [self->sets objectForKey:[NSNumber numberWithInt:setid]];
    return rslt;
}

@end

@implementation Module

-(instancetype) initWithID:(int)id andName:(NSString *)name
{
    self = [super init];
    self.id = id;
    self.name = name;
    return self;
}

@end

